/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package adara.cli;

import java.io.File;

import org.apache.commons.cli.CommandLine;

import adara.cli.CLIExecutor.CLICommand;
import adara.cli.CLIExecutor.CLIOption;

/**
 * Validates the input arguments.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public class CLIValidator {
	
	public static void validate(String command, CommandLine cli) 
		throws CLIException {
		
		if (command.equals(CLICommand.INFO)) {
			validateNumericOption(cli, CLIOption.DEVICE);
			return;
		}
		
		if (command.equals(CLICommand.CAPTURE)) {
			validateNumericOption(cli, CLIOption.DEVICE);
			validateNumericOption(cli, CLIOption.GAP);
			validateStorageOption(cli);
			
			if (cli.hasOption(CLIOption.TIME)) {
				validateNumericOption(cli, CLIOption.TIME);
			} else if (cli.hasOption(CLIOption.COUNT)) {
				validateNumericOption(cli, CLIOption.COUNT);
			}
		}
	}

	private static void validateNumericOption(CommandLine cli, String option) 
		throws CLIException {
	
		if (!cli.hasOption(option)) {
			throw new CLIException("The " + option + " is missing");
		}
		
		int value = -1;
		
		try {
			value = Integer.valueOf(cli.getOptionValue(option));
		} catch (NumberFormatException e) {
			throw new CLIException("The " + option + " is not number", e);
		}
		
		if (value < 0) {
			throw new CLIException("The " + option + " could not be negative");
		}
	}
	
	private static void validateStorageOption(CommandLine cli)
		throws CLIException {
		
		if (!cli.hasOption(CLIOption.STORAGE)) {
			throw new CLIException("Storage is not provided");
		}
		
		File storage = new File(cli.getOptionValue(CLIOption.STORAGE));
		
		if (!storage.exists() || !storage.isDirectory()) {
			throw new CLIException(
					"Storage does not exist or is not a directory");
		}
	}
}